from flask import Flask, request, render_template,redirect
from flask_uuid import FlaskUUID
from application.database import db,Base,db_init


from application.init_config import init_website_app_config, init_register_blue_point
from utils.tools.WebUtil import get_host, get_port
# define app
app = Flask(__name__, static_folder='static', static_url_path='')


# init app config
init_website_app_config(app)
init_register_blue_point(app)
FlaskUUID(app)

with app.app_context():
    db_init(app)
    db.init_app(app)
    db.create_all()


@app.before_request
def before():
    url = request.path
    #login_info = get_login_info()
    if(url=="/"):
            return redirect("/index")
    if check_url(url):
        pass
    # elif login_info != {}:
    #     if valid_login(login_info):
    #         pass
    #     else:
    #         return render_template('/common/login.html')
    # else:
    #     return render_template("/common/login.html")
    #return ""

def check_url(url):
    return url.startswith('/view') \
           or url.startswith('/index') \
           or url.startswith('/api') \
           or url.startswith('/admin') \
           or url.startswith('/api/login') \
           or url.find(".css") != -1 \
           or url.find(".js") != -1 \
           or url.find(".png") != -1 \
           or url.find(".jpg") != -1 \
           or url.find(".gif") != -1 \
           or url.find("/api/deploy/hook") != -1 \
           or url == '/' \
           or url.find(".woff") != -1 \
           or url.find(".tff") != -1 \
           or url.find(".ico") != -1 \
           or url.find("/api/contact/comment") != -1 \
           or url.find("/api/article/comment") != -1


@app.after_request
def after(environ):
    if request.path != "/login":
        print("user visit path:", request.path)
    return environ


@app.errorhandler(404)
def handle404(error):
    accept = request.headers.get("accept")
    if accept and accept.startswith('application/json'):
        print("ajax")
        return '404', 404
    # else:
    #     return render_template('public/style1/404.html'), 404


@app.errorhandler(500)
def handle500(error):
    accept = request.headers.get("accept")
    if accept and accept.startswith('application/json'):
        return '500', 500
    else:
        return '500 get',
@app.teardown_appcontext
def shutdown_session(exception=None):
    # db.session.remove()
    pass

@app.route("/favicon.ico")
def favicon():
    filename = "static/favicon.ico"
    return app.send_static_file(filename)


if __name__ == '__main__':
    app.run(host=get_host(app), port=get_port(app), debug=True)
